package com.cf.game.im.handler.hello;

import com.cf.game.im.HelloMsgService;
import com.cf.game.im.handler.AbsHandler;
import com.cf.game.im.handler.Handler;
import com.cf.game.im.model.ChatMsg;
import com.cf.game.im.model.HelloMsg;
import com.cf.game.msg.ChatMessageRequest;
import com.cf.game.msg.ChatType;
import com.cf.game.msg.MsgType;
import com.cf.mapper.BeanMapper;
import io.vertx.core.eventbus.EventBus;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * boot-game-HelloHandler
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/8/1 上午 11:44
 */
@Slf4j
@Component
public class HelloHandler extends AbsHandler implements Handler {

    @Autowired
    private BeanMapper beanMapper;

    @Autowired
    private HelloMsgService helloMsgService;

    @Override
    public void handle(Map dataMap, EventBus eventBus) {

        ChatMessageRequest chatMsg = beanMapper.map(dataMap, ChatMessageRequest.class);
        if (StringUtils.isEmpty(chatMsg.getContent())) {
            log.info("收到的消息是空消息，忽略掉！");
            return;
        }

        //欢迎消息
        if (sendHelloMsg(chatMsg, eventBus)) {
            log.info("当前发送的是欢迎消息！");
            return;
        }

    }

    private boolean sendHelloMsg(ChatMessageRequest chatMsg, EventBus ebs) {
        if (StringUtils.isNotEmpty(chatMsg.getContent()) && chatMsg.getContent().contains("[hello]")) {
            List<HelloMsg> userHelloMsg = helloMsgService.getUserHelloMsg(chatMsg.getReceiver());
            if (userHelloMsg != null && userHelloMsg.size() > 0) {
                userHelloMsg.forEach(helloMsg -> {
                    ChatMsg cMsg = new ChatMsg();
                    cMsg.setContent(helloMsg.getMsg());
                    cMsg.setAck(false);
                    cMsg.setChatTime(new Date());
                    cMsg.setMessageType(MsgType.TEXT.getType());
                    cMsg.setSender(chatMsg.getReceiver());
                    cMsg.setId(id.nextId());
                    deliveryMsg(chatMsg.getSender(), ebs, cMsg, "single");
                });
            }
            return true;
        }
        return false;
    }

    @Override
    public String getSupport() {
        return "hello";
    }

}
